let SSH = require('simple-ssh')

let execShell = function(loginInfo, cmds, level) {
    return new Promise(function (resolve) {
        let ssh = new SSH(loginInfo)
        let stack = new Set()
        ;(function _exec (level, conn, isSudo, cmd) {
            conn.exec(cmd, {
                pty: isSudo,
                out: function(stdout) {
                    switch (level) {
                        case 1:
                            if(stack.has(cmd)) break;
                            stack.add(cmd)
                            console.log(cmd)
                            break;
                        case 2:
                            stdout !== '\r\n' &&
                            stdout.replace(/\ +|\r|\n|\t/g, '') !==''  ? console.log(loginInfo.host + ":" + cmd + ':' + stdout) : ''    
                            break;
                    }
                },
                err: function(err) {
                    console.error(err)
                },
                exit: function(code) {
                    let nextCmd = cmds.shift()
                    if(code === 0){
                        if(nextCmd !== undefined) {
                            conn._commands = []
                            _exec(level, conn, isSudo, nextCmd)
                        }else {
                            console.log(loginInfo.host + ':done')
                            resolve()
                        }
                    }else if(nextCmd !== undefined) console.error(cmd + ": err :" +code)
                }
            }).start()
        }(level, ssh, !loginInfo.isroot, cmds.shift()))
    })
}

module.exports = {
    execShell: execShell
}

if (require.main === module) {
    // console.log(program.chdir)
}